using System;
using System.Collections.Generic;
using System.Text;

namespace NBusiness.Query.SqlServer
{
    public enum SqlJoinType
    {
        Inner,
        OutterLeft,
        OutterRight
    }

    public class SqlJoin : IJoin
    {
        #region Factories
        public static SqlJoin Inner(ISource source, IExpression on)
        {
            return new SqlJoin(source, on, SqlJoinType.Inner);
        }
        public static SqlJoin OutterLeft(ISource source, IExpression on)
        {
            return new SqlJoin(source, on, SqlJoinType.OutterLeft);
        }
        public static SqlJoin OutterRight(ISource source, IExpression on)
        {
            return new SqlJoin(source, on, SqlJoinType.OutterRight);
        } 
        #endregion

        #region Member fields and properties
        private ISource _source;
        private IExpression _on;
        private SqlJoinType _type;
        #endregion

        #region Constructors
        public SqlJoin(ISource source, IExpression on, SqlJoinType type)
        {
            _source = source;
            _on = on;
            _type = type;
        }
        #endregion

        #region IRelationalElement Members

        public string ToSql()
        {
            return ToSql(new SqlQueryContext());
        }
        public string ToSql(IQueryContext context)
        {
            string sql = null;
            switch (_type)
            {
                case SqlJoinType.Inner:
                    sql = "INNER JOIN " + _source.ToSql(context) + " ON " + _on.ToSql(context);
                    break;
                case SqlJoinType.OutterLeft:
                    sql = "OUTTER LEFT JOIN " + _source.ToSql(context) + " ON " + _on.ToSql(context);
                    break;
                case SqlJoinType.OutterRight:
                    sql = "OUTTER RIGHT JOIN " + _source.ToSql(context) + " ON " + _on.ToSql(context);
                    break;
            }
            return sql;
        }

        #endregion

        #region IFrom Members

        public ISource Source
        {
            get { return _source; }
        }

        public IExpression On
        {
            get { return _on; }
        }

        #endregion
    }
}
